﻿using Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Models
{
    public class XmlModel
    {
        public static XDocument ToXDoc(IEnumerable<Exercise> exercises)
        {
            var xdoc = new XDocument(new XElement("root", exercises.Select(x => new XElement("exercise", GetXContent(x)))));
            return xdoc;
        }

        private static IEnumerable<XObject> GetXContent(Exercise exercise)
        {
            yield return new XAttribute("name", exercise.DisplayName ?? "no-name");
            if (exercise.ExerciseLogs != null && exercise.ExerciseLogs.Count > 0)
            {
                foreach (var exerciseLog in exercise.ExerciseLogs)
                {
                    yield return new XElement("exLog", GetXContent(exerciseLog));
                }
            }
        }

        private static IEnumerable<XObject> GetXContent(ExerciseLog log)
        {
            yield return new XElement("date", new XAttribute("ticks", log.LogDate.Ticks), log.LogDate.ToString("yyyy MMMM dd HH:mm:ss"));
            if (log.Sets != null && log.Sets.Count > 0)
            {
                foreach (var exSet in log.Sets)
                {
                    yield return new XElement("exSet", GetXContent(exSet));
                }
            }
        }

        private static IEnumerable<XObject> GetXContent(SetLog exSet)
        {
            yield return new XAttribute("endDate", exSet.EndDateTime.Ticks);
            yield return new XAttribute("weight", exSet.Weight);
            yield return new XAttribute("reps", exSet.Repetitions);
        }
    }
}
